#
# Copyright (c) 2022 Nordic Semiconductor ASA
#
# SPDX-License-Identifier: LicenseRef-Nordic-5-Clause

'''
This script is not executed in context of "west ncs-sbom" command.
Use this script to update ../data/spdx-licenses.yaml file with newest SPDX license list.
'''

import json
import urllib.request
from pathlib import Path
from types import SimpleNamespace

import yaml

LATEST_URL = 'https://api.github.com/repos/spdx/license-list-data/releases/latest'
DOWNLOAD_URL_TMPL = 'https://raw.githubusercontent.com/spdx/license-list-data/$$$/json/licenses.json'


def escape(text):
    return text.replace("\\", "\\\\").replace("\"", "\\\"")

def download(url):
    print(f'Starting download from {url}')
    response = urllib.request.urlopen(url)
    print('Downloading...')
    binary = response.read()
    print(f'Downloaded {len(binary)} bytes')
    text = binary.decode('utf-8')
    return json.loads(text, object_hook=lambda d: SimpleNamespace(**d))

release_info = download(LATEST_URL)
download_url = DOWNLOAD_URL_TMPL.replace('$$$', release_info.tag_name)
data = download(download_url)

print(f'Number of licenses: {len(data.licenses)}')
print(f'License list version: {data.licenseListVersion}')

output = Path(__file__).parent / '../data/spdx-licenses.yaml'

try:
    with open(output) as fd:
        old = yaml.safe_load(fd)
    update = old['_version'] != data.licenseListVersion
    print(f'Old version: {old["_version"]}')
except Exception:
    print('Cannot read old version')
    update = True

data.licenses = sorted(data.licenses, key=lambda x: x.licenseId)

if update:
    print('Updating')
    with open(output, 'w') as fd:
        fd.write(f'# Autogenerated from: {download_url}\n')
        fd.write(f'_version: "{data.licenseListVersion}"\n')
        for license in data.licenses:
            fd.write(f'{license.licenseId}:\n')
            fd.write(f'  name: "{escape(license.name)}"\n')
            if license.reference != f'https://spdx.org/licenses/{license.licenseId}.html':
                fd.write(f'  URL: "{escape(license.reference)}"\n')
else:
    print('No need to update')

print('DONE')
